package buaa.paas.controller;

import buaa.paas.kubectl.ServiceUtil;
import buaa.paas.model.Response;
import io.kubernetes.client.openapi.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

@CrossOrigin(origins = {"http://localhost:8080","null"})
@RestController
@RequestMapping("/service")
public class ServiceController {
    @Autowired
    ServiceUtil serviceUtil;
    /**
     * 展示一个用户的app下面的全部的服务
     * @param aid app的id
     * @param uid 用户的id
     * */
    @PostMapping("/ls")
    public Response lsServices(
            @RequestParam("uid")String uid,
            @RequestParam("aid")String aid
    ){
        try{
            List<Map<String, Object>> result = serviceUtil.listServices(uid+"-"+aid);
            return new Response(200, result);
        }catch(ApiException e){
            return new Response(500, e.getMessage(), null);
        }
    }

    /**
     * 删除掉一个服务
     * @param uid 用户的id
     * @param aid app的id
     * @param name 被删除的服务的名字
     * */
    @PostMapping("/delete")
    public Response deleteService(
            @RequestParam("uid")String uid,
            @RequestParam("aid")String aid,
            @RequestParam("name")String name
    ){
        try{
            serviceUtil.deleteService(uid+"-"+aid, name);
            return new Response(200, null);
        }catch(ApiException e){
            return new Response(500, null);
        }
    }

    /**
     * 创建一个服务
     * */
    @PostMapping("/create")
    public Response createService(@RequestBody Map<String, Object> args){
        try{
            int uid = (int) args.get("uid");
            int aid = (int) args.get("aid");
            String name = (String) args.get("name");
            Map<String, String> labels = (Map<String, String>)args.get("labels");
            Map<String, String> selectors = (Map<String, String>) args.get("selectors");
            Map<String, String> transfers = (Map<String, String>) args.get("transfers");
            Map<Integer, Integer> transfersRemade = new TreeMap<>();
            for(String s: transfers.keySet()){
                transfersRemade.put(Integer.parseInt(s), Integer.parseInt(transfers.get(s)));
            }
            System.out.println(transfersRemade);
            serviceUtil.createService(name, uid+"-"+aid, labels, selectors, transfersRemade);
            return new Response(200, null);
        }catch(ApiException e){
            System.out.println(e.getResponseBody());
            return new Response(500, e.getMessage(), null);
        }
    }
}
